package com.zyf.connotation

import android.annotation.SuppressLint
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentActivity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup

/**
 * 作者：Think
 * 创建于 2017/5/31 14:29
 */
abstract class BaseFragment : Fragment(){
    var baseActivity: FragmentActivity? =null
    var rootView:View? = null
    private var isInit = false // 是否可以开始加载数据
    private var isLoad = false
    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        if (rootView == null) {
            rootView = initView(inflater, container)!!
            baseActivity = activity
            initFindViewById(rootView)
        }
        return rootView
    }
    override fun onDestroy() {
        super.onDestroy()
        if (rootView != null) {
            try {
                (rootView?.parent as ViewGroup).removeView(rootView)
            } catch (e: Exception) {

            }

        }
    }
    /*
     * 当Activity初始化之后可以在这里进行一些数据的初始化操作
     */
    override fun onActivityCreated(savedInstanceState: Bundle?) {
        super.onActivityCreated(savedInstanceState)
        isCanLoadData()
        initEvent()
    }
    abstract fun initView(inflater: LayoutInflater?, container: ViewGroup?):View?
    /**
     * 子类可以复写此方法初始化事件
     */
    protected fun initEvent() {

    }
    /**
     * 初始化控件
     */
    protected abstract fun initFindViewById(view: View?)
    /**
     * 子类在此方法中实现数据的初始化
     */
    abstract fun initData()
    private fun isCanLoadData() {
        if (isInit) {
            return
        }
        if (userVisibleHint) {
            isInit = true
            initData()
            isLoad = true
        }
    }
    /**
     * 视图是否已经对用户可见，系统的方法
     */
    override fun setUserVisibleHint(isVisibleToUser: Boolean) {
        super.setUserVisibleHint(isVisibleToUser)
        if(activity!=null){
            isCanLoadData()
        }
    }
}